package loader;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.TimeUnit;

public class DynamicLoader extends ClassLoader {

	public DynamicLoader(ClassLoader cl) {
		super(cl);
	}

	public Class reloadClass(String className) throws Exception {
		FileInputStream fis = new FileInputStream(className);
		System.out.println("available: " + fis.available());
		byte[] array = new byte[fis.available()];
		fis.read(array);
		URL url = new URL("file:E:\\myproject\\core\\bin\\loader\\T.class");
		URLConnection uc = url.openConnection();
		InputStream is = uc.getInputStream();
		byte[] bs = new byte[is.available()];
		is.read(bs);
		Class clz = defineClass("loader.T", bs, 0, bs.length);
		System.out.println("clz: " + clz);
		return clz;
	}

	public static void main(String[] args) throws Throwable {
		T t = new T();
		t.f();
		TimeUnit.SECONDS.sleep(10);
		DynamicLoader dl = new DynamicLoader(T.class.getClassLoader());
		T t2 = (T) dl.reloadClass("E:\\myproject\\core\\bin\\loader\\T.class").newInstance();
		t2.f();
		// E:\myproject\core\bin\loader\T.class

	}
}
